package com.hdjk.view.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.hdjk.view.R;
import com.hdjk.view.activity.main.SplashActivity;
import com.hdjk.view.config.Constant;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdateVersionService extends Service {

	private static final int DOWNLOAD_FAIL = -1;
	private static final int DOWNLOAD_SUCCESS = 0;
	
	private String mDownloadUrl = null;

	// 文件存储
	private File updateDir = null;
	private File updateFile = null;

	// 通知栏
	private NotificationManager updateNotificationManager = null;
	private Notification updateNotification = null;

	// 通知栏跳转Intent
	private Intent updateIntent = null;
	private PendingIntent updatePendingIntent = null;

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		mDownloadUrl=intent.getStringExtra("url");
		if (TextUtils.isEmpty(mDownloadUrl)) stopSelf();
		
		// 创建文件
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			updateDir = new File(Environment.getExternalStorageDirectory(),
					Constant.downLoadPath);
			updateFile = new File(updateDir.getPath(), getResources()
					.getString(R.string.app_name) + ".apk");
		}

		this.updateNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		this.updateNotification = new Notification();

		// 设置下载过程中，点击通知栏，回到主界面
		updateIntent = new Intent(this, SplashActivity.class);
		updateIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		updatePendingIntent = PendingIntent.getActivity(this, 0, updateIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);
		updateNotificationMsg("开始下载","好得财富","0%",android.R.drawable.stat_sys_download,false);

		// 开启一个新的线程下载，如果使用Service同步下载，会导致ANR问题，Service本身也会阻塞
		new Thread(new updateRunnable()).start();// 这个是下载的重点，是下载的过程

		return super.onStartCommand(intent, flags, startId);
	}
	
    /**
     * 更新通知栏上显示的信息
     */
    private void updateNotificationMsg(String tickerStr, String title, String content, int iconId,boolean isSound){
        Notification.Builder builder = new Notification.Builder(this)
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentText(content)
                .setContentIntent(updatePendingIntent)
                .setSmallIcon(iconId)
                .setWhen(System.currentTimeMillis())
                .setTicker(tickerStr);
//              .setOngoing(true);// 将Ongoing设为true 那么notification将不能滑动删除  
        if(isSound){
        	builder.setDefaults(Notification.DEFAULT_SOUND);// 铃声提醒
        }
        this.updateNotification = builder.getNotification();

        // 发出通知
        updateNotificationManager.notify(0, updateNotification);
    }

	// 接受下载信息
	private Handler updateHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case DOWNLOAD_SUCCESS :
					// 点击安装PendingIntent
					Intent installIntent = new Intent(Intent.ACTION_VIEW);
					installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					Uri apkUri;
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
						//判读版本是否在7.0以上
						apkUri = FileProvider.getUriForFile(UpdateVersionService.this, getPackageName() + ".fileprovider", updateFile);
						//添加这一句表示对目标应用临时授权该Uri所代表的文件
						installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
					} else {
						apkUri = Uri.fromFile(updateFile);
					}
					installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
					
					updatePendingIntent = PendingIntent.getActivity(UpdateVersionService.this, 0, installIntent, 0);
					updateNotificationMsg("下载完成","好得财富","下载完成,点击安装",android.R.drawable.stat_sys_download_done,true);

					startActivity(installIntent);

					// 停止服务
					// stopSelf();
					break;
				case DOWNLOAD_FAIL :
					// 下载失败
					updateNotificationMsg("下载失败","好得财富","抱歉，下载失败",android.R.drawable.stat_sys_download_done,true);
					// stopSelf();
					break;
				default :
					// stopSelf();
			}
			// 停止服务
			stopSelf();
		}
	};

	class updateRunnable implements Runnable {
		Message message = updateHandler.obtainMessage();
		public void run() {
			try {
				// 增加权限;
				if (!updateDir.exists()) {
					updateDir.mkdirs();
				}
				if (!updateFile.exists()) {
					updateFile.createNewFile();
				}
				// 下载函数，以QQ为例子
				// 增加权限;
				long downloadSize = downloadUpdateFile(mDownloadUrl, updateFile);

				if (downloadSize > 0) {
					Intent intent = new Intent(Constant.INTENT_FILTER_STRING_UPDATE_APK_FINISH);
					intent.putExtra("is_success", true);
					sendBroadcast(intent);
					// 下载成功
					message.what = DOWNLOAD_SUCCESS;
					updateHandler.sendMessage(message);
				}
			} catch (Exception ex) {
				ex.printStackTrace();
				Intent intent = new Intent(Constant.INTENT_FILTER_STRING_UPDATE_APK_FINISH);
				intent.putExtra("is_success", false);
				sendBroadcast(intent);
				// 下载失败
				message.what = DOWNLOAD_FAIL;
				updateHandler.sendMessage(message);
			}
		}
	}
	public long downloadUpdateFile(String downloadUrl, File saveFile)
			throws Exception {
		// 这样的下载代码很多，我就不做过多的说明
		int downloadCount = 0;
		int currentSize = 0;
		long totalSize = 0;
		int updateTotalSize = 0;

		HttpURLConnection httpConnection = null;
		InputStream is = null;
		FileOutputStream fos = null;

		try {
			URL url = new URL(downloadUrl);
			httpConnection = (HttpURLConnection) url.openConnection();
			httpConnection
					.setRequestProperty("User-Agent", "PacificHttpClient");
			if (currentSize > 0) {
				httpConnection.setRequestProperty("RANGE", "bytes="
						+ currentSize + "-");
			}
			httpConnection.setConnectTimeout(10000);
			httpConnection.setReadTimeout(20000);
			updateTotalSize = httpConnection.getContentLength();
			if (httpConnection.getResponseCode() == 404) {
				throw new Exception("fail!");
			}
			is = httpConnection.getInputStream();
			fos = new FileOutputStream(saveFile, false);
			byte buffer[] = new byte[4096];
			int readsize = 0;
			while ((readsize = is.read(buffer)) > 0) {
				fos.write(buffer, 0, readsize);
				totalSize += readsize;
				// 为了防止频繁的通知导致应用吃紧，百分比增加10才通知一次
				if ((downloadCount == 0)
						|| (int) (totalSize * 100 / updateTotalSize) - 1 > downloadCount) {
					downloadCount += 1;
					int curProgress= (int) (totalSize * 100 / updateTotalSize);
					
					Intent intent=new Intent(Constant.INTENT_FILTER_STRING_UPDATE_APK_FINISH);
					intent.putExtra("progress", curProgress+ "%");
					sendBroadcast(intent);//发送一个广播
					
					updateNotificationMsg("正在下载","好得财富", "已下载"+ curProgress + "%",android.R.drawable.stat_sys_download,false);
				}
			}
		} finally {
			if (httpConnection != null) {
				httpConnection.disconnect();
			}
			if (is != null) {
				is.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
		return totalSize;
	}

}
